package com.ulife.order.service.util;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by Ulife on 2016/1/25.
 */
public class HttpUtil {
    private  static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /*
    * http post
    * */
    public static String httpPost(String url, String requestData, Charset charset, String contentType) {
        if (url == null || url.isEmpty() || requestData == null || requestData.isEmpty()) return null;

        logger.info("url:".concat(url).concat("\t request data:".concat(requestData)));

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        CloseableHttpResponse httpResponse = null;
        try {
            ContentType contentTypeX = ContentType.create(contentType, charset);
            StringEntity requestEntity = new StringEntity(requestData, contentTypeX);
            post.setEntity(requestEntity);
            // 执行post请求
            httpResponse = httpClient.execute(post);
            // 取得响应结果
            HttpEntity entity = httpResponse.getEntity();
            if (entity == null) {
                return null;
            }
            // 响应的对象字符串
            String rtn = EntityUtils.toString(entity, charset);
            logger.info("response:".concat(rtn == null ? "" : rtn));
            return rtn;
        } catch (Exception e) {
            logger.error("支付信息发送失败！失败信息:{}.".concat(e.toString()));
        } finally {
            // 关闭资源
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}
